package cn.pcios.kindle;

import java.util.concurrent.Executor;

import javax.sql.DataSource;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import cn.pcios.kindle.scheduler.Scheduler;

@EnableScheduling
@SpringBootApplication
public class KindleDownApplication {
	private static final Logger logger = LoggerFactory.getLogger(KindleDownApplication.class); 
	@Value("${config.dbfilehome}")
	String dbfilehome;
	@Value("${config.dbType}")
	String dbType;

	@Bean
	public DataSource dataSource() {
		DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
		dataSourceBuilder.driverClassName(dbType);
		dataSourceBuilder.url(dbfilehome);
		return dataSourceBuilder.build();
	}

	@Value("${Executor.corePoolSize}")
	private int corePoolSize;// 线程池维护线程的最少数量
	@Value("${Executor.maxPoolSize}")
	private int maxPoolSize;// 线程池维护线程的最大数量
	@Value("${Executor.queueCapacity}")
	private int queueCapacity; // 缓存队列
	@Value("${Executor.keepAlive}")
	private int keepAlive;// 允许的空闲时间

	@Bean
	public Executor myExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);
		executor.setMaxPoolSize(maxPoolSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setThreadNamePrefix("mqExecutor-");
		// rejection-policy：当pool已经达到max size的时候，如何处理新任务
		// CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 对拒绝task的处理策略
		executor.setKeepAliveSeconds(keepAlive);
		executor.initialize();
		return executor;
	}

	public static void main(String[] args) {
		SpringApplication.run(KindleDownApplication.class, args);
	}
}
